package cn.tedu.sp11.fiiter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import sun.security.krb5.internal.ccache.FileCCacheConstants;

import javax.jnlp.FileContents;
import javax.servlet.http.HttpServletRequest;


/**
 * @outhor wuyanzu
 * @date 2021- 03- 31
 */
@Component
public class AccessFilter  extends ZuulFilter {
    @Override
    public String filterType() {
       //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        /**
         * 如果调用商品，必须登录才能调用
         * 调用其他服务不必登录
         */
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String)ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase((serviceId));
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        if(StringUtils.isEmpty(token)){
            ctx.setSendZuulResponse(false);
            String json = JsonResult
                    .err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("Not login! 没有登录！")
                    .toString();//转成json字符串
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null;
    }
}
